
let EventEmitter = require('eventemitter3');

const templateDiv = `
    <span id="name"></span>
    <input type="checkbox" id="box">
`;

class CheckBox{

    constructor(name='',checked = false) {
        this._checked = false;

        this.element = globalThis.document.createElement('div');
        this.element.innerHTML = templateDiv;

        this.nameEl = this.element.querySelector('#name');
        this.nameEl.innerText = name;
        this.inputEl = this.element.querySelector('#box');
        this.inputEl.addEventListener('change',this.onUIChanged.bind(this),false);

         this.ee = new EventEmitter();
         this.ee.on('check',this.onDataChange,this);

         this.setChecked(checked);
    }

    setChecked(value){
        this._checked = !!value;
        this.ee.emit('check',this._checked);
    }

    // data-> ui
    onDataChange(newValue){
        this.inputEl.checked = !!newValue;
    }

    // ui-> data
    onUIChanged(){
        this.setChecked(!!this.inputEl.checked);
        console.log('checked:',this._checked);
    }
}

module.exports = CheckBox;
